package backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 40. 组合总和 II
 * User: Li_yizYa
 * Date: 2025/6/16
 * Time: 21:58
 */
public class Solution5 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return ret;
        }
        Arrays.sort(candidates);
        List<Integer> tmp = new ArrayList<>();
        backTracking(ret, tmp, candidates, target, 0, 0);
        return ret;
    }
    private void backTracking(List<List<Integer>> ret, List<Integer> tmp, int[] candidates, int target, int sum, int index) {
        if (sum == target) {
            ret.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (sum + candidates[i] > target) {
                return;
            }
            // 去重
            if (i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            tmp.add(candidates[i]);
            backTracking(ret, tmp, candidates, target, sum + candidates[i], i + 1);
            tmp.remove(tmp.size() - 1);
        }
    }
}
